library(GenomicFeatures)
plotRanges <- function(x, xlim = x, main = deparse(substitute(x)),
                       col = "black", sep = 0.5, ...){
  height <- 1
  if (is(xlim, "Ranges"))
    xlim <- c(min(start(xlim)), max(end(xlim)))
  bins <- disjointBins(IRanges(start(x), end(x) + 1))
  plot.new()
  par(mai=c(0.6, 0.2, 0.6, 0.2))
  plot.window(xlim, c(0, max(bins)*(height + sep)))
  ybottom <- bins * (sep + height) - height
  rect(start(x)-0.5, ybottom, end(x)+0.5, ybottom + height, col = col, ...)
  title(main, cex.main=2.8, font.main=1)
  axis(1)
}




## genome range
sel.bl<-bl[sel.gis==gi.list,c(6:10)]
attach(sel.bl)
strt<-hfrom
ed<-hto
strt[hfrom>hto]<-hto[hfrom>hto]
ed[hfrom>hto]<-hfrom[hfrom>hto]
hdif<-hto-hfrom
hdif[hdif<0]<-"-"
hdif[hdif!="-"]<-"+"
ir<-IRanges(start=strt, end=ed)
##ir<-IRanges(hfrom, width=abs(hto-hfrom))
cvg<-coverage(reduce(ir))
##flg<-which(cvg.val==1)
##best.cvg<-sum(runLength(cvg)[flg])/sel.contig.len

gr<-GRanges(seqnames = head(letters, 9), ranges=ir, strand=Rle(hdif))##, seqinfo=Seqinfo(head(letters,9), width(ir), NA, "seq")) 

autoplot(gr, stat="coverage", geom="area")
autoplot(gr, aes(y = value), geom = "point")



hit.len<-width(reduce(ir))
gr<-GRanges(seqnames = as.character(1:9), ranges=reduce(ir), strand=Rle(hdif), seqinfo=Seqinfo(as.character(1:9), as.numeric(hit.len), NA, "seq"))
##tiff(paste("figures/blast_best_", target.name, ".tiff", sep=""), width=1400, height=100)
print(ggplot(reduce(gr)) + geom_rect() + theme(axis.ticks.x=NULL, axis.ticks.margin =unit(c(0,0,0,0), "mm"), plot.margin = unit(c(0,0,0,0), "mm"), panel.margin = unit(c(0,0,0,0), "mm"), legend.margin= unit(c(0,0,0,0), "mm")), vp = vplayout(1, 1))
##ggplot(gr)
##dev.off()


detach(sel.bl)
sel.contig.len<-nchar(contig.seqs[sel.contig.name])



gr <-GRanges(seqnames = Rle(c("chr1", "chr2", "chr1", "chr3"), c(1, 3, 2, 3)),
             ranges = IRanges(1:9, width = c(1,2,3,1,3,4,6,7,10), names = head(letters,9)),
             strand = Rle(strand(c("-", "+", "*", "+", "-")), c(1, 2, 2, 3, 1)),
             seqinfo=seqinfo)

